package com.lk.server.rpc.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @author kun.li
 */
public class InitializerHandler extends ChannelInitializer<NioSocketChannel> {
    MessageCodec messageCodec = new MessageCodec();
    RequestMessageHandler requestMessageHandler = new RequestMessageHandler();

    @Override
    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
        ChannelPipeline pipeline = nioSocketChannel.pipeline();
        HeartBeatServerHandler heartBeatServerHandler = new HeartBeatServerHandler();
        // 空闲时间检查
        //  在服务器端会每隔10秒来检查一下channelRead方法被调用的情况，如果在10秒内该链上的channelRead方法都没有被触发，就会调用userEventTriggered方法。
        pipeline.addLast("server-idle-handler", new IdleStateHandler(0, 0, 60*2, SECONDS));
        // 增加handler链
        // 用来处理黏包和半包问题
        pipeline.addLast(new ProcotolFrameDecoder());
        // 日志打印
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
        // 编解码handler
        pipeline.addLast(messageCodec);
        pipeline.addLast(heartBeatServerHandler);
        // 自定义handler
        pipeline.addLast(requestMessageHandler);

    }
}
